package com.rzx.mybackend.config.excutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ExcutorConfig
 *
 * @author renzhexian
 * @date 2025/9/19
 */
@Configuration
public class ExecutorConfig {

    // 混合型任务
    public static final int DEFAULT_CORE_POOL_SIZE = 16;  // 核心线程数
    public static final int DEFAULT_MAXIMUM_POOL_SIZE = 32;  // 最大线程数（考虑超线程）
    public static final int DEFAULT_KEEP_ALIVE_TIME = 60;
    public static final int DEFAULT_QUEUE_SIZE = 200;
    public static final String DEFAULT_THREAD_NAME_PREFIX = "async-pool-";

    @Bean("commonTaskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(DEFAULT_CORE_POOL_SIZE);
        executor.setMaxPoolSize(DEFAULT_MAXIMUM_POOL_SIZE);
        executor.setKeepAliveSeconds(DEFAULT_KEEP_ALIVE_TIME);
        executor.setQueueCapacity(DEFAULT_QUEUE_SIZE);
        executor.setThreadNamePrefix(DEFAULT_THREAD_NAME_PREFIX);
        // 配置拒绝策略：确保任务一定会被执行，不会被丢弃
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
